package com.dragon.sdgp.util;

import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class CacheUtil {
    static Map<String, Long> verificationCodeCache = new HashMap<>();

    static {
        new Thread(()->{
            while (true){
                try {
                    Thread.currentThread().sleep(2 * 60 * 1000);
                    for (String code : verificationCodeCache.keySet()) {
                        if(verificationCodeCache.containsKey(code)){
                            if(verificationCodeCache.get(code) <= System.currentTimeMillis()){
                                verificationCodeCache.remove(code);
                                log.info("verificationCodeCache remove => {}", code);
                            }
                        }
                    }
                } catch (Exception e) {

                }
            }
        }).start();
    }

    public static void put(String code, long expire){
        log.info("put ==> <{}, {}>", code, expire);
        verificationCodeCache.put(code, System.currentTimeMillis() + expire);
    }

    public static String get(String key){
        if(verificationCodeCache.containsKey(key)) {
            if(verificationCodeCache.get(key) > System.currentTimeMillis()){
                verificationCodeCache.remove(key);
                log.info("verificationCodeCache remove => {}", key);
                return key;
            }
        }
        return null;
    }
}
